﻿using IISLogAnalyzer.Common;
using IISLogAnalyzer.DbHelper;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Globalization;
using System.Linq;
using System.Runtime.InteropServices.ComTypes;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;

namespace IISLogAnalyzer
{
    public partial class FormCharts : Form
    {
        private string _typesString = "sum(_sc_bytes) vals ";
        private string minDate = "";
        private string maxDate = "";
        private string unite = "MB";

        public FormCharts(string maxDate, string minDate)
        {
            InitializeComponent();

            this.maxDate = maxDate;
            this.minDate = minDate;

            dtpDateEnd.Text = this.maxDate;
            dtpDateStart.Text = this.minDate;
        }

        #region 选择分析类型
        /// <summary>
        /// 选择分析类型
        /// </summary>
        private void SetTypesSqlString()
        {
            switch (cbxTypes.Text)
            {
                case "发送字节":
                    _typesString = "sum(_sc_bytes) vals ";
                    unite = "MB";
                    break;
                case "接收字节":
                    _typesString = "sum(_cs_bytes) vals ";
                    unite = "KB";
                    break;
                case "耗时毫秒":
                    _typesString = "sum(_time_taken) vals ";
                    unite = "S";
                    break;
                case "访问数量":
                    _typesString = "count(1) vals ";
                    unite = "B";
                    break;
            }
        }
        #endregion

        #region 绑定服务器
        /// <summary>
        /// 绑定服务器
        /// </summary>
        public void BindServer()
        {
            DataSet ds = SqlServerHelper.Query("SELECT DISTINCT [_s_computername] as title,[_s_ip] as ip from dt_iis_logs_analyzer order by _s_computername ;");

            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("ip");
                dt.Columns.Add("title");

                DataRow dr = dt.NewRow();
                dr["ip"] = "0";
                dr["title"] = "所有服务器";

                dt.Rows.Add(dr);

                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    dr = dt.NewRow();
                    dr["ip"] = ds.Tables[0].Rows[i]["ip"].ToString();
                    dr["title"] = ds.Tables[0].Rows[i]["title"].ToString();
                    dt.Rows.Add(dr);
                }

                ControlProxyHelper.SetProperty(this, "cbxServerName", "DisplayMember", "title");
                ControlProxyHelper.SetProperty(this, "cbxServerName", "ValueMember", "ip");
                ControlProxyHelper.SetProperty(this, "cbxServerName", "DataSource", dt);
                ControlProxyHelper.SetProperty(this, "cbxServerName", "SelectedIndex", 0);
            }
        }


        #endregion

        #region 绑定网站
        /// <summary>
        /// 绑定网站
        /// </summary>
        public void BindWebSites()
        {
            if (ControlProxyHelper.GetValue(cbxServerName, "SelectedIndex").ToString() == "0")
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("index");
                dt.Columns.Add("title");

                DataRow dr = dt.NewRow();
                dr["index"] = "0";
                dr["title"] = "所有网站";

                dt.Rows.Add(dr);

                ControlProxyHelper.SetProperty(this, "cbxWebSites", "DisplayMember", "title");
                ControlProxyHelper.SetProperty(this, "cbxWebSites", "ValueMember", "index");
                ControlProxyHelper.SetProperty(this, "cbxWebSites", "DataSource", dt);
                ControlProxyHelper.SetProperty(this, "cbxWebSites", "SelectedIndex", 0);
                return;
            }

            DataSet ds = SqlServerHelper.Query("SELECT DISTINCT [_s_sitename] as title from dt_iis_logs_analyzer order by _s_sitename;");

            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("index");
                dt.Columns.Add("title");

                DataRow dr = dt.NewRow();
                dr["index"] = "0";
                dr["title"] = "所有网站";

                dt.Rows.Add(dr);

                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    dr = dt.NewRow();
                    dr["index"] = (i + 1).ToString();
                    dr["title"] = ds.Tables[0].Rows[i]["title"].ToString();
                    dt.Rows.Add(dr);
                }

                ControlProxyHelper.SetProperty(this, "cbxWebSites", "DisplayMember", "title");
                ControlProxyHelper.SetProperty(this, "cbxWebSites", "ValueMember", "index");
                ControlProxyHelper.SetProperty(this, "cbxWebSites", "DataSource", dt);
                ControlProxyHelper.SetProperty(this, "cbxWebSites", "SelectedIndex", 0);
            }

        }
        #endregion

        #region 加载总对比饼图

        private void InitializePieChartTotal()
        {
            StringBuilder stringBuilder = new StringBuilder();

            stringBuilder.Append("select _s_computername,_s_sitename, " + _typesString + " ");
            stringBuilder.Append("from dt_iis_logs_analyzer ");
            stringBuilder.Append("where _date between '" + Utils.ObjectToDateTime(dtpDateStart.Text, DateTime.Now).ToString("yyyy-MM-dd") + "' and '" + Utils.ObjectToDateTime(dtpDateEnd.Text, DateTime.Now).ToString("yyyy-MM-dd") + "' ");

            if (cbxServerName.SelectedIndex > 0)
            {
                stringBuilder.Append(" and [_s_computername] = '" + cbxServerName.Text + "' ");
            }

            if (cbxWebSites.SelectedIndex > 0)
            {
                stringBuilder.Append(" and [_s_sitename] = '" + cbxWebSites.Text + "' ");
            }

            stringBuilder.Append("group by _s_computername,_s_sitename;");

            DataSet ds = SqlServerHelper.Query(stringBuilder.ToString());

            if (Utils.CheckDataSet(ds))
            {
                int days = (Utils.ObjectToDateTime(dtpDateEnd.Text) - Utils.ObjectToDateTime(dtpDateStart.Text)).Days;

                // 清除所有现有系列  
                chartPie1.Series.Clear();

                // 创建一个新的Series对象  
                Series pieSeries = new Series("PieSeries");

                // 设置Series的ChartType为Pie  
                pieSeries.ChartType = SeriesChartType.Pie;

                // 添加数据点  
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    // 添加数据点
                    var dataPoint = new DataPoint();
                    dataPoint.CustomProperties = "_s_computername=" + dr["_s_computername"].ToString();
                    dataPoint.XValue = 0;
                    dataPoint.YValues = new double[] { Math.Round(Utils.GetByteValueWithUnit(Utils.ObjToDouble(dr["vals"]), "MB"), 2) };

                    // 设置自定义图例文本
                    dataPoint.Label = dr["_s_sitename"].ToString() + "\n\r " + dataPoint.YValues[0] + "M"; // 将自定义文本存储在Tag属性中

                    dataPoint.LegendText = dr["_s_sitename"].ToString();

                    // 添加数据点到饼图系列
                    pieSeries.Points.Add(dataPoint);
                }

                // 计算饼图系列中所有点的YValue之和  
                double total = pieSeries.Points.Sum(p => p.YValues[0]);

                // 遍历数据系列中的每个数据点  
                foreach (DataPoint point in pieSeries.Points)
                {
                    // 检查当前点的值是否占整个饼图的10%或以上  
                    double percentage = (point.YValues[0] / total) * 100;
                    if (percentage >= 10)
                    {
                        point.IsValueShownAsLabel = true; // 确保值作为标签显示  
                    }
                    else
                    {
                        point.Label = " ";
                        point.IsValueShownAsLabel = false; // 不显示值作为标签  
                    }
                }

                // 将Series添加到Chart控件中  
                chartPie1.Series.Add(pieSeries);
                // 刷新图表以显示更改  
                chartPie1.Invalidate();
                // 刷新图表以显示更改  
                chartPie1.Refresh();

                string totals = "";

                switch (unite)
                {
                    case "MB":
                        totals = "发送 " + Math.Round(Utils.GetByteValueWithUnit(total * 1024d * 1024d, "GB"), 2) + " GB";
                        break;
                    case "KB":
                        totals = "接收 " + Math.Round(Utils.GetByteValueWithUnit(total * 1024d * 1024d, "MB"), 2) + " MB";
                        break;
                    case "S":
                        totals = "耗时 " + Math.Round(Utils.GetByteValueWithUnit(total * 1024d * 1024d, "KB"), 2) + " 秒";
                        break;
                    case "B":
                        totals = "访问 " + Math.Round(Utils.GetByteValueWithUnit(total * 1024d * 1024d, "B"), 2) + " 次";
                        break;
                }

                gbPieChartTotal.Text = "总对比：" + ds.Tables[0].Rows.Count + "个网站，" + (days + 1) + "天，" + totals;

                SetMaxCoutAndIp();
            }
        }


        #endregion

        #region 加载单分析饼图

        private void InitializePieChartSingle(string _s_sitename)
        {
            lbxDomain.Items.Clear();
            gbxDomain.Text = "域名列表";
            if (_s_sitename != "")
            {
                DataSet dataSet = SqlServerHelper.Query("SELECT DISTINCT [_cs_host] as title from dt_iis_logs_analyzer where _s_sitename = '" + _s_sitename + "' order by _cs_host;");
                if (Utils.CheckDataSet(dataSet))
                {
                    gbxDomain.Text = "<---单分析的域名列表";
                    foreach (DataRow dr in dataSet.Tables[0].Rows)
                    {
                        lbxDomain.Items.Add(dr[0].ToString());
                    }
                }
            }

            lbSiteName.Text = _s_sitename;

            StringBuilder stringBuilder = new StringBuilder();

            int days = (Utils.ObjectToDateTime(dtpDateEnd.Text) - Utils.ObjectToDateTime(dtpDateStart.Text)).Days;

            if (days > 0)
            {
                stringBuilder.Append("select _date," + _typesString + " ");
                stringBuilder.Append("from dt_iis_logs_analyzer ");
                stringBuilder.Append("where _date between '" + Utils.ObjectToDateTime(dtpDateStart.Text, DateTime.Now).ToString("yyyy-MM-dd") + "' and '" + Utils.ObjectToDateTime(dtpDateEnd.Text, DateTime.Now).ToString("yyyy-MM-dd") + "' ");
                if (HidSelectedServerName.Text != "")
                {
                    stringBuilder.Append(" and [_s_computername] = '" + HidSelectedServerName.Text + "' ");
                }
                stringBuilder.Append("and _s_sitename = '" + _s_sitename + "' ");
                stringBuilder.Append("group by _date ORDER BY _date;");
            }
            else if (days == 0)
            {
                stringBuilder.Append("select DATEPART(HOUR, CAST(_time AS datetime)) AS HourGroup," + _typesString + " ");
                stringBuilder.Append("from dt_iis_logs_analyzer ");
                stringBuilder.Append("where _date between '" + Utils.ObjectToDateTime(dtpDateStart.Text, DateTime.Now).ToString("yyyy-MM-dd") + "' and  '" + Utils.ObjectToDateTime(dtpDateEnd.Text, DateTime.Now).ToString("yyyy-MM-dd") + "' ");
                if (HidSelectedServerName.Text != "")
                {
                    stringBuilder.Append(" and [_s_computername] = '" + HidSelectedServerName.Text + "' ");
                }
                stringBuilder.Append("and _s_sitename = '" + _s_sitename + "' ");
                stringBuilder.Append("group by DATEPART(HOUR, CAST(_time AS datetime)) ORDER BY HourGroup;");
            }
            else
            {
                return;
            }

            DataSet ds = SqlServerHelper.Query(stringBuilder.ToString());

            if (Utils.CheckDataSet(ds))
            {
                // 清除所有现有系列  
                chartPie2.Series.Clear();

                // 创建一个新的Series对象  
                Series pieSeries = new Series("单分析");

                // 设置Series的ChartType为Pie  
                pieSeries.ChartType = SeriesChartType.Doughnut;

                // 添加数据点  
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    // 添加数据点
                    var dataPoint = new DataPoint();
                    dataPoint.XValue = 0;
                    dataPoint.YValues = new double[] { Math.Round(Utils.GetByteValueWithUnit(Utils.ObjToDouble(dr["vals"]), "MB"), 2) };

                    // 设置自定义图例文本
                    dataPoint.Label = days > 0 ? Utils.ObjectToDateTime(dr["_date"]).ToString("yyyy-MM-dd") : dr["HourGroup"].ToString(); // 将自定义文本存储在Tag属性中

                    dataPoint.LegendText = days > 0 ? Utils.ObjectToDateTime(dr["_date"]).ToString("yyyy-MM-dd") : dr["HourGroup"].ToString();

                    // 添加数据点到饼图系列
                    pieSeries.Points.Add(dataPoint);
                }

                // 计算饼图系列中所有点的YValue之和  
                double total = pieSeries.Points.Sum(p => p.YValues[0]);


                // 遍历数据系列中的每个数据点  
                foreach (DataPoint point in pieSeries.Points)
                {
                    // 检查当前点的值是否占整个饼图的10%或以上  
                    double percentage = (point.YValues[0] / total) * 100;
                    if (percentage >= (days > 0 ? 10 : 4))
                    {
                        point.IsValueShownAsLabel = true; // 确保值作为标签显示  
                    }
                    else
                    {
                        point.Label = " ";
                        point.IsValueShownAsLabel = false; // 不显示值作为标签  
                    }
                }

                // 将Series添加到Chart控件中  
                chartPie2.Series.Add(pieSeries);
                // 刷新图表以显示更改  
                chartPie2.Invalidate();
                // 刷新图表以显示更改  
                chartPie2.Refresh();

                string totals = "";

                switch (unite)
                {
                    case "MB":
                        totals = "发送 " + Math.Round(Utils.GetByteValueWithUnit(total * 1024d * 1024d, "GB"), 2) + " GB";
                        break;
                    case "KB":
                        totals = "接收 " + Math.Round(Utils.GetByteValueWithUnit(total * 1024d * 1024d, "MB"), 2) + " MB";
                        break;
                    case "S":
                        totals = "耗时 " + Math.Round(Utils.GetByteValueWithUnit(total * 1024d * 1024d, "KB"), 2) + " 秒";
                        break;
                    case "B":
                        totals = "访问 " + Math.Round(Utils.GetByteValueWithUnit(total * 1024d * 1024d, "B"), 2) + " 次";
                        break;
                }

                if (days > 0)
                {
                    gbPieChartSingle.Text = "单分析：" + _s_sitename + "：" + (days + 1) + "天，" + totals;
                }
                else
                {
                    gbPieChartSingle.Text = "单分析：" + _s_sitename + "：24小时内，" + totals;
                }

                SetMaxCoutAndIp(1);
            }
        }


        #endregion

        #region 详细分析柱状图
        private void InitializeColumnChart(string _date_time)
        {
            // 清除所有现有系列  
            ChartColumn.Series.Clear();

            HidIsDay.Text = _date_time;
            bool isDay = true;
            string format = "yyyy-MM-dd"; // 期望的日期格式  
            CultureInfo provider = CultureInfo.InvariantCulture; // 使用的文化信息，这里使用不变文化信息  

            DateTime result;
            bool isDateValid = DateTime.TryParseExact(_date_time, format, provider, DateTimeStyles.None, out result);

            if (isDateValid)
            {
                lbDataTime.Text = _date_time + " 24小时内数据";
            }
            else
            {
                isDay = false;
                lbDataTime.Text = _date_time == "23" ? "(23 ~ 0)点内的数据" : "(" + (_date_time + " ~ " + (Convert.ToInt32(_date_time) + 1)) + ")点内的内数据";
            }

            StringBuilder stringBuilder = new StringBuilder();

            if (isDay)
            {
                stringBuilder.Append("select DATEPART(HOUR, CAST(_time AS datetime)) AS HourGroup," + _typesString + " ");
                stringBuilder.Append("from dt_iis_logs_analyzer ");
                stringBuilder.Append("where _date = '" + _date_time + "' ");
                stringBuilder.Append("and _s_sitename = '" + lbSiteName.Text + "' ");
                if (HidSelectedServerName.Text != "")
                {
                    stringBuilder.Append(" and [_s_computername] = '" + HidSelectedServerName.Text + "' ");
                }
                stringBuilder.Append("group by DATEPART(HOUR, CAST(_time AS datetime)) ORDER BY HourGroup;");
            }
            else
            {
                int minute = 1;
                stringBuilder.Append("select (DATEPART(MINUTE, CAST(_time AS DATETIME)) / " + minute + ") * " + minute + " AS MinuteGroup," + _typesString + " ");
                stringBuilder.Append("from dt_iis_logs_analyzer ");
                stringBuilder.Append("where _date = '" + Utils.ObjectToDateTime(dtpDateStart.Text).ToString("yyyy-MM-dd") + "' ");
                stringBuilder.Append("and _s_sitename = '" + lbSiteName.Text + "' ");
                stringBuilder.Append("and DATEPART(HOUR, CAST(_time AS DATETIME)) = " + _date_time + " ");
                if (HidSelectedServerName.Text != "")
                {
                    stringBuilder.Append(" and [_s_computername] = '" + HidSelectedServerName.Text + "' ");
                }
                stringBuilder.Append("group by DATEPART(HOUR, CAST(_time AS DATETIME)),(DATEPART(MINUTE, CAST(_time AS DATETIME)) / " + minute + ") * " + minute + " order by MinuteGroup;");
            }

            DataSet ds = SqlServerHelper.Query(stringBuilder.ToString());

            if (Utils.CheckDataSet(ds))
            {
                DataTable dt = ds.Tables[0].Clone();

                if (isDay)
                {
                    for (int i = 0; i < 24; i++) { DataRow dr = dt.NewRow(); dr["HourGroup"] = i; dt.Rows.Add(dr); }
                }
                else
                {
                    for (int i = 0; i < 59; i++) { DataRow dr = dt.NewRow(); dr["MinuteGroup"] = i; dt.Rows.Add(dr); }
                }

                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    DataRow[] matchingRowsB = dt.Select((isDay ? "HourGroup" : "MinuteGroup") + " = '" + (isDay ? Convert.ToDouble(dr["HourGroup"].ToString()) : Convert.ToDouble(dr["MinuteGroup"].ToString())) + "'");

                    if (matchingRowsB.Length > 0)
                    {
                        DataRow rowB = matchingRowsB[0]; // 假设每个日期在B中只有一个匹配项  
                        foreach (DataColumn col in ds.Tables[0].Columns)
                        {
                            if (col.ColumnName != (isDay ? "HourGroup" : "MinuteGroup")) // 跳过日期列，因为它已经匹配了  
                            {
                                rowB[col.ColumnName] = dr[col.ColumnName]; // 将A中的数据复制到B中  
                            }
                        }
                    }
                }

                // 创建一个新的Series对象  
                Series columnSeries = new Series("详细分析");

                // 设置Series的ChartType为Column  
                columnSeries.ChartType = SeriesChartType.Column;

                double maxY = 0;
                // 添加数据点  
                foreach (DataRow dr in dt.Rows)
                {
                    // 添加数据点
                    var dataPoint = new DataPoint();
                    dataPoint.XValue = isDay ? Convert.ToDouble(dr["HourGroup"].ToString()) : Convert.ToDouble(dr["MinuteGroup"].ToString());

                    double yv = 0;

                    switch (unite)
                    {
                        case "MB":
                            yv = Math.Round(Utils.GetByteValueWithUnit(Utils.ObjToDouble(dr["vals"]), "MB"), 2);
                            break;
                        case "KB":
                            yv = Math.Round(Utils.GetByteValueWithUnit(Utils.ObjToDouble(dr["vals"]), "KB"), 2);
                            break;
                        case "S":
                            yv = Math.Round(Utils.GetByteValueWithUnit(Utils.ObjToDouble(dr["vals"]), "KB"), 2);
                            break;
                        case "B":
                            yv = Math.Round(Utils.GetByteValueWithUnit(Utils.ObjToDouble(dr["vals"]), "B"), 2);
                            break;
                    }

                    if (yv > maxY)
                    {
                        maxY = yv;
                    }

                    dataPoint.YValues = new double[] { yv };

                    dataPoint.AxisLabel = isDay ? dr["HourGroup"].ToString() + " 时" : dr["MinuteGroup"].ToString() + " 分钟";

                    if (yv > 0)
                    {
                        // 设置自定义图例文本

                        switch (unite)
                        {
                            case "MB":
                                dataPoint.Label = yv.ToString("0.00") + "M"; // 将自定义文本存储在Tag属性中
                                break;
                            case "KB":
                                dataPoint.Label = yv.ToString("0.00") + "K"; // 将自定义文本存储在Tag属性中
                                break;
                            case "S":
                                dataPoint.Label = yv.ToString("0.00") + "S"; // 将自定义文本存储在Tag属性中
                                break;
                            case "B":
                                dataPoint.Label = yv.ToString("0.00") + ""; // 将自定义文本存储在Tag属性中
                                break;
                        }

                    }
                    else
                    {// 设置自定义图例文本
                        dataPoint.Label = ""; // 将自定义文本存储在Tag属性中                        
                    }

                    // 添加数据点到饼图系列
                    columnSeries.Points.Add(dataPoint);
                }

                ChartColumn.ChartAreas[0].AxisY.Maximum = Math.Floor(maxY) + 1;

                ChartColumn.Series.Add(columnSeries);

                if (!isDay)
                {
                    ChartColumn.ChartAreas[0].AxisX.LabelStyle.Angle = -45; // 设置标签角度为-45度，使其倾斜显示
                }

                ChartColumn.ChartAreas[0].AxisX.Interval = 1;

                // 设置X轴和Y轴线条加粗  
                ChartColumn.ChartAreas[0].AxisX.LineWidth = 2;
                ChartColumn.ChartAreas[0].AxisY.LineWidth = 2;

                // 设置X轴和Y轴刻度线为浅灰色虚线  
                ChartColumn.ChartAreas[0].AxisX.MajorGrid.LineColor = Color.LightGray;
                ChartColumn.ChartAreas[0].AxisX.MajorGrid.LineDashStyle = ChartDashStyle.Dash;
                ChartColumn.ChartAreas[0].AxisY.MajorGrid.LineColor = Color.LightGray;
                ChartColumn.ChartAreas[0].AxisY.MajorGrid.LineDashStyle = ChartDashStyle.Dash;

                // 如果需要设置次要刻度线，也可以这样设置  
                ChartColumn.ChartAreas[0].AxisX.MinorGrid.LineColor = Color.LightGray;
                ChartColumn.ChartAreas[0].AxisX.MinorGrid.LineDashStyle = ChartDashStyle.Dash;
                ChartColumn.ChartAreas[0].AxisY.MinorGrid.LineColor = Color.LightGray;
                ChartColumn.ChartAreas[0].AxisY.MinorGrid.LineDashStyle = ChartDashStyle.Dash;

                // 刷新图表以显示更改  
                ChartColumn.Refresh();
                // 刷新图表以显示更改  
                ChartColumn.Invalidate();

                // 计算饼图系列中所有点的YValue之和  
                double total = ChartColumn.Series[0].Points.Sum(p => p.YValues[0]);

                switch (unite)
                {
                    case "MB":
                        lbCounts.Text = "发送 " + Math.Round(Utils.GetByteValueWithUnit(total * 1024d * 1024d, "GB"), 2) + " GB";
                        break;
                    case "KB":
                        lbCounts.Text = "接收 " + Math.Round(Utils.GetByteValueWithUnit(total * 1024d * 1024d, "MB"), 2) + " MB";
                        break;
                    case "S":
                        lbCounts.Text = "耗时 " + Math.Round(Utils.GetByteValueWithUnit(total * 1024d * 1024d, "KB"), 2) + " 秒";
                        break;
                    case "B":
                        lbCounts.Text = "访问 " + Math.Round(Utils.GetByteValueWithUnit(total * 1024d * 1024d, "B"), 2) + " 次";
                        break;
                }

                SetMaxCoutAndIp(2);
            }
        }
        #endregion                

        #region 开始分析
        private void btnOk_Click(object sender, EventArgs e)
        {
            chartPie1.Series.Clear();

            gbPieChartSingle.Text = "单分析";
            chartPie2.Series.Clear();
            gbColumnChart.Text = "详细分析";
            ChartColumn.Series.Clear();
            lbDataTime.Text = "--";
            lbSiteName.Text = "--";

            IpCount.Text = "--";
            IpCountSingle.Text = "--";
            IpCountTotal.Text = "--";
            IpTimes.Text = "--";
            IpTimesSingle.Text = "--";
            IpTimesTotal.Text = "--";

            HidSelectedServerName.Text = "";
            HidIsDay.Text = "";

            InitializePieChartTotal();
        }

        #endregion

        #region 点击总对比图扇区处理方法

        private void chartPie_MouseClick(object sender, MouseEventArgs e)
        {
            // 使用 HitTest 方法来获取点击的位置信息
            HitTestResult result = chartPie1.HitTest(e.Location.X, e.Location.Y);

            // 检查是否点击在数据点上
            if (result.ChartElementType == ChartElementType.DataPoint)
            {
                // 获取被点击的数据点对象
                DataPoint dp = result.Series.Points[result.PointIndex] as DataPoint;

                // 检查是否是饼图的数据点
                if (dp != null && chartPie1.Series[0].ChartType == SeriesChartType.Pie)
                {
                    try
                    {
                        HidSelectedServerName.Text = dp.CustomProperties.Substring(dp.CustomProperties.IndexOf("=") + 1);
                    }
                    catch
                    {
                        HidSelectedServerName.Text = "";
                    }

                    InitializePieChartSingle(dp.LegendText);
                }
            }
        }

        private void chartPie2_MouseClick(object sender, MouseEventArgs e)
        {
            // 使用 HitTest 方法来获取点击的位置信息
            HitTestResult result = chartPie2.HitTest(e.Location.X, e.Location.Y);

            // 检查是否点击在数据点上
            if (result.ChartElementType == ChartElementType.DataPointLabel || result.ChartElementType == ChartElementType.DataPoint)
            {
                // 获取被点击的数据点对象
                DataPoint dp = result.Series.Points[result.PointIndex] as DataPoint;

                // 检查是否是饼图的数据点
                if (dp != null && chartPie2.Series[0].ChartType == SeriesChartType.Doughnut)
                {
                    InitializeColumnChart(dp.LegendText);
                }
            }
        }

        #endregion

        #region 设置最大访问数和IP

        /// <summary>
        /// 设置最大访问数和IP
        /// </summary>
        /// <param name="index">0总对比，1单分析，2详细分析</param>
        private void SetMaxCoutAndIp(int index = 0)
        {
            StringBuilder stringBuilder = new StringBuilder();
            DataSet ds = new DataSet();
            switch (index)
            {
                case 0:
                    stringBuilder.Append("select _c_ip,count(_c_ip) counts from dt_iis_logs_analyzer where id > 0 ");

                    if (cbxServerName.SelectedIndex > 0)
                    {
                        stringBuilder.Append(" and [_s_computername] = '" + cbxServerName.Text + "' ");
                    }

                    if (cbxWebSites.SelectedIndex > 0)
                    {
                        stringBuilder.Append(" and [_s_sitename] = '" + cbxWebSites.Text + "' ");
                    }

                    stringBuilder.Append(" group by _c_ip order by count(_c_ip) desc");

                    ds = SqlServerHelper.Query(stringBuilder.ToString());

                    if (Utils.CheckDataSet(ds))
                    {
                        IpCountTotal.Text = ds.Tables[0].Rows[0]["counts"].ToString();
                        IpTimesTotal.Text = ds.Tables[0].Rows[0]["_c_ip"].ToString();
                    }

                    break;
                case 1:
                    stringBuilder.Append("select _c_ip,count(_c_ip) counts from dt_iis_logs_analyzer where id > 0 ");

                    if (HidSelectedServerName.Text != "")
                    {
                        stringBuilder.Append(" and [_s_computername] = '" + HidSelectedServerName.Text + "' ");
                    }

                    if (lbSiteName.Text != "")
                    {
                        stringBuilder.Append(" and [_s_sitename] = '" + lbSiteName.Text + "' ");
                    }

                    stringBuilder.Append(" group by _c_ip order by count(_c_ip) desc");

                    ds = SqlServerHelper.Query(stringBuilder.ToString());

                    if (Utils.CheckDataSet(ds))
                    {
                        IpCountSingle.Text = ds.Tables[0].Rows[0]["counts"].ToString();
                        IpTimesSingle.Text = ds.Tables[0].Rows[0]["_c_ip"].ToString();
                    }

                    break;
                case 2:

                    string format = "yyyy-MM-dd"; // 期望的日期格式  
                    CultureInfo provider = CultureInfo.InvariantCulture; // 使用的文化信息，这里使用不变文化信息  

                    DateTime result;
                    bool isDateValid = DateTime.TryParseExact(HidIsDay.Text, format, provider, DateTimeStyles.None, out result);

                    stringBuilder.Append("select _c_ip,count(_c_ip) counts from dt_iis_logs_analyzer where id > 0 ");

                    if (isDateValid)
                    {
                        stringBuilder.Append(" and _date = '" + HidIsDay.Text + "' ");
                    }
                    else
                    {
                        stringBuilder.Append(" and _date = '" + Utils.ObjectToDateTime(dtpDateStart.Text).ToString("yyyy-MM-dd") + "' ");
                        stringBuilder.Append(" and DATEPART(HOUR, CAST(_time AS DATETIME)) = " + HidIsDay.Text + " ");
                    }

                    stringBuilder.Append(" group by _c_ip order by count(_c_ip) desc");

                    ds = SqlServerHelper.Query(stringBuilder.ToString());

                    if (Utils.CheckDataSet(ds))
                    {
                        IpCount.Text = ds.Tables[0].Rows[0]["counts"].ToString();
                        IpTimes.Text = ds.Tables[0].Rows[0]["_c_ip"].ToString();
                    }

                    break;
            }
        }
        #endregion

        private void dtpDateStart_ValueChanged(object sender, EventArgs e)
        {
            if (Utils.ObjectToDateTime(dtpDateStart.Value) < Utils.ObjectToDateTime(minDate))
            {
                dtpDateStart.Text = minDate;
            }
        }

        private void dtpDateEnd_ValueChanged(object sender, EventArgs e)
        {
            if (Utils.ObjectToDateTime(dtpDateEnd.Value) > Utils.ObjectToDateTime(maxDate))
            {
                dtpDateEnd.Text = maxDate;
            }
        }

        private void cbxServerName_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindWebSites();
        }

        private void FormCharts_Load(object sender, EventArgs e)
        {
            cbxTypes.SelectedIndex = 0;
            BindServer();
        }

        private void cbxTypes_SelectedIndexChanged(object sender, EventArgs e)
        {
            SetTypesSqlString();
        }

        private void cbxWebSites_SelectedIndexChanged(object sender, EventArgs e)
        {
            lbxDomain.Items.Clear();
            gbxDomain.Text = "域名列表";
            if (cbxWebSites.SelectedIndex > 0)
            {
                DataSet dataSet = SqlServerHelper.Query("SELECT DISTINCT [_cs_host] as title from dt_iis_logs_analyzer where _s_sitename = '" + cbxWebSites.Text + "' order by _cs_host;");
                if (Utils.CheckDataSet(dataSet))
                {
                    gbxDomain.Text = "分析网站的域名列表--->";
                    foreach (DataRow dr in dataSet.Tables[0].Rows)
                    {
                        lbxDomain.Items.Add(dr[0].ToString());
                    }
                }
            }
        }
    }
}
